package utils;


import java.awt.Component;
import java.awt.Container;

import constants.GlobalDebug;
import controller.ShapeController;
import figures.ShapeContainer;
import figures.WBShape;

public class ObjectReadWrite {
    
    public static void loadFromFile(Container parent, ShapeController controler,String filname) {
	
	//FP
	controler.clearAll();
	ObjectReader reader = ObjectReader.openFileForReading(filname);
	ShapeContainer c = (ShapeContainer) (reader.readObject());
	Component[] arrayShapes = c.getComponents();
	if (GlobalDebug.isOn)
	    System.out
		    .println("ShapeController.ActionPerformed(): Read "
			    + arrayShapes.length
			    + " shapes from the file");
	for (int i = 0; i < arrayShapes.length; i++) {
	    WBShape s = (WBShape) arrayShapes[i];
	    parent.add(s);
	    s.addMouseListener(controler);
	    s.addMouseMotionListener(controler);
	    if (GlobalDebug.isOn)
		 System.out.println(s.asString());
	}
	reader.close();
	parent.repaint();
    }

    public static void saveToFile(Container parent,String filname) {
	ObjectWriter writer = ObjectWriter.openFileForWriting(filname);
	ShapeContainer sc = new ShapeContainer();
	Component[] arrayShapes = parent.getComponents();
	for (int i = 0; i < arrayShapes.length; i++) {
	    WBShape s = (WBShape) ((WBShape) arrayShapes[i]).clone();
	    s.setSelectState(false);
	    sc.add(s);
	}

	if (GlobalDebug.isOn)
	    System.out.println("ShapeController.ActionPerformed(): Written "
		    + parent.getComponentCount()
		    + " shapes to the file");
	writer.writeObject(sc);
	writer.close();
    }

}
